import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import { withTranslation } from 'next-i18next';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import { toast } from '@/components/basicComp/Toast';
import ConfirmationDialog from '@/components/basicComp/CloseDialog';

import { motion } from 'framer-motion';
import * as Switch from '@radix-ui/react-switch';
import { executeAuthorization, delInstallPlugin, enabledPlugin } from '@/api/plugins';
import _ from 'lodash';

@withTranslation('common')
@withRouter
@connect(({ }) => ({}))
class Comp extends Component {
  state = {
    open: false, // 是否打开删除确认弹窗
    delServerName:'',//删除接口 需要的
  }

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  constructor(props) {
    super(props);
    this.debouncedHandleTogglePlugin = _.debounce(this.handleTogglePlugin.bind(this), 300);
    this.debouncedHandleEnabledPlugin = _.debounce(this.handleEnabledPlugin.bind(this), 300);
  }

  handleTogglePlugin = async (params) => {
    let rs = await executeAuthorization(params);
    if (rs.data?.code == 200) {
      this.props?.getInstallList();
    } else {
      toast.error(rs?.data?.sub_message);
    }
  };

  getPluginIcon = (name) => {
    // Simple function to return an icon based on plugin name
    // In a real implementation, you might use actual icons
    const firstLetter = name.charAt(0).toUpperCase();
    return <div className={styles.pluginIcon}><img src={this.props?.getImg(name)} /></div>
    //  <div className={styles.pluginIcon}>{firstLetter}</div>;
  };
  // 编辑
  handleInstall = async (plugin) => {
    let newEnv = Object.keys(plugin?.env).map((item => {
      return { key: item, isRequired: true, value: plugin?.env[item] }
    }))
    let newPlugin = { ...plugin };
    newPlugin.newEnv = newEnv;
    let newArgs = plugin?.args.map(item => {
      return { isRequired: true, value: item }
    })
    newPlugin.newArgs = newArgs;
    newPlugin.isEdit = true;
    console.log('newPlugin: ', newPlugin);
    // 打开弹窗
    this.props?.openAddCustomPlugin(newPlugin);
    this.props?.changeModalTitle('Edit Plugin'); // 设置弹窗标题
  };

  // 删除
  handleDelPlugin = async (params) => {
    const { delServerName } = this.state;
    let rs = await delInstallPlugin({server_name:delServerName});
    if (rs.data?.code == 200) {
      //调用 列表接口
      this.props?.getInstallList();
      this.handleConfirmatIsOpen(); // 关闭弹窗
    } else {
      toast.error(rs?.data?.sub_message);
    }
  }
  // 启用插件
  handleEnabledPlugin = async (params) => {
    let rs = await enabledPlugin(params);
    if (rs.data?.code == 200) {
      //调用 列表接口
      this.props?.getInstallList();
    } else {
      toast.error(rs?.data?.sub_message);
    }
  }
  // 点击打开删除确认弹窗
  handleConfirmatIsOpen = () => {
    this.setState({
      open: !this.state.open
    })
  }





  render() {
    const { installPluginList } = this.props;
    const { open } = this.state;
    return (
      <motion.div
        initial={{ opacity: 0 }} // 初始状态：不透明度为 0
        animate={{ opacity: 1 }} // 动画状态：不透明度为 1
        transition={{ duration: 0.5 }} // 动画持续时间为 1 秒
        style={{ height: '100%' }}
      >
        <div value={this.controller}>
          <div className={styles.container}>
            {/* Plugins Grid */}
            <div className={styles.pluginsGrid}>
              {installPluginList?.map((plugin, index) => (
                <div className={styles.pluginCard}>
                  <div
                    key={`${plugin.name}-${index}`}
                    className={styles.pluginCardTop}
                  >

                    {this.getPluginIcon(plugin.server_name)}
                    <div className={styles.pluginInfo}>
                      <div className={styles.pluginName}>{plugin.server_name}</div>
                      <div className={styles.pluginNamespace}>
                        {plugin.server_description}
                      </div>
                    </div>

                    <div className={styles.status}>
                      <Switch.Root
                        className={styles.switchRoot}
                        checked={plugin?.enabled}
                        onCheckedChange={(e) =>
                          this.debouncedHandleEnabledPlugin({ server_name: plugin.server_name, mcp_enabled: e })
                        }
                      >
                        <Switch.Thumb className={styles.switchThumb} />
                      </Switch.Root>
                    </div>
                  </div>
                  <div className={styles.pluginCardBottom}>
                    {/* 是否开启自动授权 */}
                    {plugin?.execute_authorization ? <div className={styles.running} onClick={() => {
                      this.debouncedHandleTogglePlugin({ server_name: plugin.server_name, execute_authorization: false })
                    }}>
                      <i className={styles.round}></i>
                      <span>Always Allow</span>
                    </div> : <div className={styles.closed} onClick={() => {
                      this.debouncedHandleTogglePlugin({ server_name: plugin.server_name, execute_authorization: true })
                    }}>
                      <i className={styles.round}></i>
                      <span>Always Ask</span>
                    </div>
                    }
                    <div className={styles.actions} >
                      {/* 编辑 */}
                      <span className={styles.edit} onClick={() => {
                        this.handleInstall(plugin)
                      }}><i className='iconfont icon-yulan'></i></span>
                      {/* 删除 */}
                      <span onClick={() => {
                        this.setState({
                          delServerName:plugin.server_name 
                        },()=>{
                          this.handleConfirmatIsOpen();
                        })
                        
                        // this.handleDelPlugin({ server_name: plugin.server_name })
                      }} className={styles.del}><i className='iconfont icon-Delete'></i></span>

                    </div>
                  </div>
                </div>

              ))}
            </div>
          </div>
          {/* 删除确认框 */}
          <ConfirmationDialog
            open={open}
            onOpenChange={this.handleConfirmatIsOpen}
            onConfirm={this.handleDelPlugin}
            title='Delete Plugin'
            description='Are you sure you want to delete this plugin? This cannot be undone.'
          />
        </div>
      </motion.div>
    );
  }
}

export default Comp;
